//
//  AppDelegate+JiGuang.m
//  BaseProject
//
//  Created by 王盼盼 on 2024/9/10.
//  Copyright © 2024 wangpanpan. All rights reserved.
//

#import "AppDelegate+JiGuang.h"
#import <AdSupport/AdSupport.h>
#import <JVERIFICATIONService.h>
// iOS10 注册 APNs 所需头文件
# ifdef NSFoundationVersionNumber_iOS_9_x_Max
# import <UserNotifications/UserNotifications.h>
# endif
#import "TSPushNotificationView.h"
@implementation AppDelegate (JiGuang)
- (void)initJiGuangWithOption:(NSDictionary *)launchingOption {
    [self initJVerification];
    [self initJPushWithOption:launchingOption];
}

/// 一键认证
- (void)initJVerification {
    JVAuthConfig *config = [[JVAuthConfig alloc]init];
    config.appKey = S.appKey_jiguang;
    config.advertisingId = S.uuid;
    config.timeout = 5000;
    [config setAuthBlock:^(NSDictionary * _Nonnull result) {
        NSLog(@"极光认证初始化 %@", [result[@"code"] intValue] == 8000 ? @"success" : @"fail");
    }];
    [JVERIFICATIONService setupWithConfig:config];
#if DEBUG
    //[JVERIFICATIONService setDebug:YES];
    // 隐藏log
    [JVERIFICATIONService setDebug:NO];
    config.isProduction = NO;
#else
    [JVERIFICATIONService setDebug:NO];
    config.isProduction = YES;
#endif
    if ([JVERIFICATIONService isSetupClient]) {
        [JVERIFICATIONService preLogin:5000 completion:^(NSDictionary * _Nonnull result) {
            NSLog(@"极光认证预取号 %@", [result[@"code"] intValue] == 7000 ? @"success" : @"fail");
        }];
    }
}

- (void)initJPushWithOption:(NSDictionary *)launchingOption {
    JPUSHRegisterEntity *entity = [[JPUSHRegisterEntity alloc] init];
    if (@available(iOS 12.0, *)) {
        entity.types =
        JPAuthorizationOptionAlert|
        JPAuthorizationOptionBadge|
        JPAuthorizationOptionSound|
        JPAuthorizationOptionProvidesAppNotificationSettings;
    } else {
        entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    }
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
      // 可以添加自定义 categories
      // NSSet<UNNotificationCategory *> *categories for iOS10 or later
      // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    // 新版本的注册方法（兼容iOS10）
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    // 启动SDK 
    [JPUSHService setupWithOption:launchingOption appKey:S.appKey_jiguang channel:S.jiguang_channel apsForProduction:kRelease advertisingIdentifier:S.uuid];
    // 日志
    //[JPUSHService setDebugMode];
    // 关闭日志
    [JPUSHService setLogOFF];
    // JPush标识此设备的
    [JPUSHService registrationIDCompletionHandler:^(int resCode, NSString * _Nullable registrationID) {
        NSLog(@"极光设备id%@", registrationID);
        [Utilities setToNSUserDefaults:@"BA_registrationID" value:registrationID];
        if ([TTUserModel sharedObject].token.length > 0) {
            // 设置Alias
            [JPUSHService setAlias:[NSString stringWithFormat:@"%@", [TTUserModel sharedObject].username] completion:^(NSInteger iResCode, NSString * _Nullable iAlias, NSInteger seq) {
                NSLog(@"设置Alias %ld %@", iResCode, iAlias);
            } seq:1];
            //2.设置标签
            /*
            NSMutableSet *set = [NSMutableSet set];
            [set addObject:@"帅哥"];
            [JPUSHService setTags:set completion:^(NSInteger iResCode, NSSet *iTags, NSInteger seq) {
                NSLog(@"%@",iTags);
            } seq:1];
             */
            //3.设置手机号
            /**
             [JPUSHService setMobileNumber:xxx completion:^(NSError *error) {
                 NSLog(@"%@",error);
             }];
             */
            
        }
    }];
    // 置空
    [self setbadge:0];
}
- (void)setbadge:(NSInteger)badge {
    [JPUSHService setBadge:badge]; //同步本地角标值到服务器
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:badge]; //APP 显示角标需开
}
#pragma mark - AppDelegate
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    // Required - 注册 DeviceToken
    const unsigned int *tokenBytes = [deviceToken bytes];
    NSString *tokenString = [NSString stringWithFormat:@"%08x%08x%08x%08x%08x%08x%08x%08x",
                          ntohl(tokenBytes[0]), ntohl(tokenBytes[1]), ntohl(tokenBytes[2]),
                          ntohl(tokenBytes[3]), ntohl(tokenBytes[4]), ntohl(tokenBytes[5]),
                          ntohl(tokenBytes[6]), ntohl(tokenBytes[7])];
    NSLog(@"极光推送设备的Device Token: %@", tokenString);
    [JPUSHService registerDeviceToken:deviceToken];
    [TTUserModel sharedObject].deviceToken = deviceToken;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}
//基于 iOS 7 及以上的系统版本，如果是使用 iOS 7 的 Remote Notification 特性那么处理函数需要使用
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
#pragma mark - JPUSHRegisterDelegate
// 监测通知授权状态返回的结果
- (void)jpushNotificationAuthorization:(JPAuthorizationStatus)status withInfo:(nullable NSDictionary *)info {
    
}

- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center openSettingsForNotification:(nonnull UNNotification *)notification {
    if (notification && [notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        //从通知界面直接进入应用
        NSLog(@"极光推送从通知界面直接进入应用");
    } else {
        //从通知设置界面进入应用
        NSLog(@"极光推送从通知设置界面进入应用");
    }
}

- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center willPresentNotification:(nonnull UNNotification *)notification withCompletionHandler:(nonnull void (^)(NSInteger))completionHandler {
    //NSDictionary * userInfo = notification.request.content.userInfo;
    //UNNotificationRequest *request = notification.request; // 收到推送的请求
    //UNNotificationContent *content = request.content; // 收到推送的消息内容
    //NSNumber *badge = content.badge;  // 推送消息的角标
    //NSString *body = content.body;    // 推送消息体
    //UNNotificationSound *sound = content.sound;  // 推送消息的声音
    //NSString *subtitle = content.subtitle;  // 推送消息的副标题
    //NSString *title = content.title;  // 推送消息的标题
    // 前台
    if ([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        // 远程通知
        [JPUSHService handleRemoteNotification:notification.request.content.userInfo];
    } else {
        // 本地通知
    }
    completionHandler(UNNotificationPresentationOptionBadge|UNNotificationPresentationOptionSound|UNNotificationPresentationOptionAlert);
}

- (void)jpushNotificationCenter:(nonnull UNUserNotificationCenter *)center didReceiveNotificationResponse:(nonnull UNNotificationResponse *)response withCompletionHandler:(nonnull void (^)(void))completionHandler {
    // 后台
    if ([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:response.notification.request.content.userInfo];
        [self handlePush:response.notification.request.content.userInfo];
    } else {
        
    }
    completionHandler();
}


- (void)handlePush:(NSDictionary *)userInfo {
    if ([userInfo.allKeys containsObject:@"customAttribute"]) {
        //后台推送
        NSString *customAttribute = userInfo[@"customAttribute"];
        NSData *data = [customAttribute dataUsingEncoding:NSUTF8StringEncoding];
        NSDictionary *json = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",json);
        //HomeADItemEventModel
        HomeADItemEventModel *eventModel = [HomeADItemEventModel modelWithJSON:json];
        [[TT_JumpManager sharedManager]jumpWithModel:eventModel completion:^(BOOL success, NSString * _Nonnull message) {
            
        }];
    }
}
@end
